<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use App\Models\TempVerificationCode;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'code' => ['required', 'digits:6'],  // 添加验证码验证
        ]);
    }

    // 重写 register 方法
    public function register(Request $request)
    {
        Log::info('开始处理注册请求', $request->all());

        $this->validator($request->all())->validate();

        Log::info('验证通过，开始检查验证码');

        // 验证码最终检查
        $verificationCode = TempVerificationCode::where('email', $request->email)
            ->where('code', $request->code)
            ->where('type', 'register')
            ->first();

        if (!$verificationCode || $verificationCode->expired_at < now()) {
            Log::warning('验证码检查失败', [
                'email' => $request->email,
                'code' => $request->code,
                'verification_exists' => (bool)$verificationCode,
                'expired' => $verificationCode ? $verificationCode->expired_at < now() : null
            ]);
            return back()->withErrors(['code' => '验证码无效或已过期']);
        }

        Log::info('验证码检查通过，开始创建用户');

        $user = $this->create($request->all());

        Log::info('用户创建成功，开始清理验证码');

        try {
            // 记录删除前的验证码数量
            $beforeCount = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->count();

            // 删除所有与该邮箱相关的验证码记录
            $deleted = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->delete();

            // 记录删除后的验证码数量
            $afterCount = TempVerificationCode::where('email', $request->email)
                ->where('type', 'register')
                ->count();

            Log::info('验证码删除操作完成', [
                'email' => $request->email,
                'before_count' => $beforeCount,
                'deleted_count' => $deleted,
                'after_count' => $afterCount
            ]);

        } catch (\Exception $e) {
            Log::error('删除验证码失败', [
                'email' => $request->email,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }

        Log::info('注册流程完成，准备登录');

        $this->guard()->login($user);

        Log::info('用户已登录，准备跳转');

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}
